
package com.evriko.commenterall.impl.appengine.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.evriko.commenterall.api.dao.ReviewDao;
import com.evriko.commenterall.api.pojo.IReview;
import com.evriko.commenterall.api.pojo.Review;
import com.evriko.commenterall.api.pojo.Source;
import com.evriko.commenterall.persistence.PMF;
import com.evriko.commenterall.persistence.pReview;
import com.evriko.commenterall.server.ReviewManagerImpl;
import com.evriko.commenterall.server.ReviewsCriteria;
import com.google.appengine.api.datastore.Text;

/**
 * @author Volodymyr.Petrusha vladimir@petrusha.net
 * @version $Id ReviewDaoAppengineImpl.java 17:51:08
 */
public class ReviewDaoAppengineImpl implements ReviewDao {
	private static final Logger log = Logger.getLogger(ReviewManagerImpl.class.getName());
	
	
	public List<IReview> getReviewsByCriteria(ReviewsCriteria criteria) {
		List<Review> reviews = new ArrayList<Review>();
		PersistenceManager pm = PMF.getFactory().getPersistenceManager();
		String query = buildQuery(criteria);
		
		Query pmQuery = pm.newQuery(query);
		Collection<?> result = (Collection<?>) pmQuery.execute();
		
		Iterator<?> itr = result.iterator();  
		while (itr.hasNext()) {
			pReview review = (pReview) itr.next();
			reviews.add( buildReview(review) ); 
		}
		
		return (List<IReview>) (null == reviews ? Collections.emptyList() : reviews);
	}

	
	private Review buildReview(pReview review) {
		return new Review(
				review.getId(),
				new Source(), 
				review.getAuthor(), 
				review.getText().
				getValue(), 
				review.getDate());
	}

	
	protected String buildQuery(ReviewsCriteria criteria) {
		StringBuilder sb = new StringBuilder("select from")
		.append(" ")
		.append(pReview.class.getName())
		.append(" order by ")
		.append(criteria.getOrderBy())
		.append(" ")
		.append(criteria.getOrder())
		.append(" range ")
		.append(criteria.getStart())
		.append(",")
		.append(criteria.getStart() + criteria.getCount());
		
		return sb.toString();
	}


	public Boolean saveReview(Review review) {
		PersistenceManager pm = PMF.getFactory().getPersistenceManager();
		Boolean flag = true;
        try {
            pm.makePersistent(buildPReview(review));
        } catch (Exception e) {
			log.log(Level.WARNING, e.getMessage());
			flag = false;
		} finally {
            pm.close();
        }
		return flag;
	}


	private pReview buildPReview(Review review) {
		return new pReview(
				review.getId(), 
				review.getAuthor(), 
				new Text(review.getText()), 
				review.getDate());		
	}
	
}
